package com.imy.lua.activity.screen;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.imy.common.base.BaseOnePxActivity;
import com.imy.common.helper.ParamsHelper;
import com.imy.lua.helper.screen.Shooter;
import com.imy.common.util.ALog;
import com.imy.lua.LuaCore;

public class ScreenActivity extends BaseOnePxActivity {
    public static final int REQUEST_MEDIA_PROJECTION = 0x2304;
    private String TAG = "ScreenActivity";
    private static final int DEFAULT_DELAY = 100;
    private int delay = 100;

    public static void start(Context context, String path) {
        int orientation = LuaCore.get().getAccessibilityServiceListener().getOrientation();
        ALog.i("ScreenActivity:" + orientation);
        Intent intent;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            intent = new Intent(context, ScreenActivity.class);
        } else {
            intent = new Intent(context, ScreenLandscapeActivity.class);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ParamsHelper.DATA, DEFAULT_DELAY);
        intent.putExtra(ParamsHelper.PATH, path);
        context.startActivity(intent);
        ALog.i("screenActivity start");
    }

    public static void start(Context context, String path, int delay) {
        Intent intent = new Intent(context, ScreenActivity.class);
        intent.putExtra(ParamsHelper.DATA, delay);
        intent.putExtra(ParamsHelper.PATH, path);
        context.startActivity(intent);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
//        hideSystemNav();
        ALog.i("screenActivity init");
        this.delay = getIntent().getIntExtra(ParamsHelper.DATA, DEFAULT_DELAY);
        requestScreenShotPermission();
    }

    private void requestScreenShotPermission() {
        if (Build.VERSION.SDK_INT >= 21) {
            startActivityForResult(createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
        }
    }

    private String getPath() {
        return getIntent().getStringExtra(ParamsHelper.PATH);
    }

    private Intent createScreenCaptureIntent() {
        //here used media_projection instead of Context.MEDIA_PROJECTION_SERVICE to  make it successfully build on low api.
        return ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)).createScreenCaptureIntent();
    }

    private void hideSystemNav() {
        if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = getWindow().getDecorView();
            final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flags);
            decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    if (isFinishing()) {
                        return;
                    }
                    if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                        decorView.setSystemUiVisibility(getShowInputFlags());
                    } else if (visibility == 4) {
                        decorView.setSystemUiVisibility(flags);
                    }
                }
            });
        }

    }

    private int getShowInputFlags() {
        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        return flags;
    }

    @Override
    protected void onDestroy() {
        shooter.release();
        super.onDestroy();
    }

    private Shooter shooter;

    protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_MEDIA_PROJECTION: {
                if (resultCode == RESULT_OK && data != null) {
                    getWindow().getDecorView().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            shooter = new Shooter(ScreenActivity.this, resultCode, data);
                            shooter.startScreenShot(getPath(), new Shooter.OnShotListener() {
                                @Override
                                public void onFinish(String path) {
                                    Log.i(TAG, "onFinish path:" + path);
                                    Intent intent = new Intent();
                                    intent.setData(Uri.parse(path));
                                    setResult(RESULT_OK, intent);
                                    finish(); // don't forget finish activity
                                    //跨进程通讯
                                    callBack(path);


                                }

                                @Override
                                public void onError() {
                                    setResult(RESULT_CANCELED);
                                    finish();
                                    callBack("");
                                }
                            });
                        }
                    }, delay);
                } else if (resultCode == RESULT_CANCELED) {
                    setResult(RESULT_CANCELED);
                    finish();
                    callBack("");
                } else {
                    setResult(RESULT_CANCELED);
                    finish();
                    callBack("");
                }
            }
        }
    }

    private void callBack(String path) {
        String packageName = getPackageName();
        String uri = packageName + ".screen.provider";
        Uri parse = Uri.parse("content://" + uri);
        ContentResolver contentResolver = getContentResolver();
        Cursor query = contentResolver.query(parse, null, path,
                null, null);
        if (query != null) {
            query.close();
        }
    }

}
